package com.rxsk.cas.component;

import cn.hutool.core.date.DateUtil;
import com.rxsk.cas.constant.SecurityRedisKeyConstant;
import com.rxsk.cas.exception.JwtTokenException;
import com.rxsk.cas.pojo.UserDetailPlus;
import com.rxsk.cas.properties.CasProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JwtToken生成的工具类
 * JWT token的格式：header.payload.signature
 * header的格式（算法、token的类型）：
 * {"alg": "HS512","typ": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 */
@Slf4j
@Configuration
public class JwtTokenUtil {

    private static final String CLAIM_KEY_USER_ID = "user_id";

    private static final String CLAIM_KEY_USERNAME = "user_name";

    private static final String CLAIM_KEY_CREATED = "created";

    @Resource
    private CasProperties casProperties;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 根据负责生成JWT的token
     *
     * @param claims     token内容
     * @param expiration 有效时长，单位：秒
     */
    private String generateToken(Map<String, Object> claims, Long expiration) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate(expiration))
                .signWith(SignatureAlgorithm.HS512, casProperties.getJwtSecretKey())
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(casProperties.getJwtSecretKey())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     *
     * @param expiration 有效时长，单位：秒
     */
    private Date generateExpirationDate(Long expiration) {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.get(CLAIM_KEY_USERNAME, String.class);
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 从token中获取登录id
     */
    public Long getUserIdFromToken(String token) {
        Long userId;
        try {
            Claims claims = getClaimsFromToken(token);
            userId = claims.get(CLAIM_KEY_USER_ID, Long.class);
        } catch (Exception e) {
            userId = null;
        }
        return userId;
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetailPlus userDetails) {
        if (StringUtils.isBlank(token) || userDetails == null) {
            return false;
        }
        String username = getUserNameFromToken(token);
        if (StringUtils.isBlank(username)) {
            return false;
        }
        if (!username.equals(userDetails.getUsername())) {
            return false;
        }
        if (isTokenExpired(token)) {
            return false;
        }
        String key = buildRedisKey(userDetails);
        String keyValue = redisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(keyValue) || !token.equals(keyValue)) {
            return false;
        }
        return true;
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据用户信息生成token
     *
     * @param userDetails 用户信息
     * @param expiration  有效时长（单位：秒）
     * @return
     */
    public String generateToken(UserDetailPlus userDetails, Long expiration) {
        if (userDetails == null || StringUtils.isBlank(userDetails.getUsername())) {
            throw new JwtTokenException("用户信息不能空");
        }
        if (expiration == null) {
            throw new JwtTokenException("token有效时长不能空");
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USER_ID, userDetails.getUserId());
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claims, expiration);
    }

    /**
     * 生成redis key
     *
     * @param userDetails
     * @return
     */
    public String buildRedisKey(UserDetailPlus userDetails) {
        if (userDetails == null || StringUtils.isBlank(userDetails.getUsername())) {
            throw new JwtTokenException("用户信息不能空");
        }
        String key = SecurityRedisKeyConstant.USER_LOGIN_TOKEN + userDetails.getUsername();
        return key;
    }

    /**
     * 当原来的token没过期时是可以刷新的
     *
     * @param oldToken   带tokenHead的token
     * @param expiration 有效时长，单位：秒
     */
    public String refreshHeadToken(String oldToken, Long expiration) {
        if (StringUtils.isEmpty(oldToken)) {
            return null;
        }
        String token = oldToken.substring(casProperties.getJwtTokenPrefix().length());
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        //token校验不通过
        Claims claims = getClaimsFromToken(token);
        if (claims == null) {
            return null;
        }
        //如果token已经过期，不支持刷新
        if (isTokenExpired(token)) {
            return null;
        }
        //如果token在30分钟之内刚刷新过，返回原token
        if (tokenRefreshJustBefore(token, 30 * 60)) {
            return token;
        } else {
            claims.put(CLAIM_KEY_CREATED, new Date());
            return generateToken(claims, expiration);
        }
    }

    /**
     * 判断token在指定时间内是否刚刚刷新过
     *
     * @param token 原token
     * @param time  指定时间（秒）
     */
    private boolean tokenRefreshJustBefore(String token, int time) {
        Claims claims = getClaimsFromToken(token);
        Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
        Date refreshDate = new Date();
        //刷新时间在创建时间的指定时间内
        if (refreshDate.after(created) && refreshDate.before(DateUtil.offsetSecond(created, time))) {
            return true;
        }
        return false;
    }
}
